import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // 定义5秒超时
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
// 状态码错误判断
// 数据脱壳
service.interceptors.response.use(
  response => {
    if (response.data.success) {
      return response.data
    } else {
      return Promise.reject(new Error(response.data.message))
    }
  },
  // 在响应拦截器这里根据浏览器状态10002是token过期，清除state中数据，跳转到login页面获取当前页面的路径
  async error => {
    console.log('请求出错了', error)
    if (error.response.data.code === 10002) {
      await store.dispatch('user/logout')
      router.push('/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath))
    }
    console.dir(error)
    return Promise.reject(error)
  }
)

export default service
